using System;
using System.Windows.Forms;
using System.Reflection;

namespace Meta
{
	/// <summary>
	/// Summary description for FlagMenuItem.
	/// </summary>
	public class StaticFlagMenuItem : MenuItem
	{
		public StaticFlagMenuItem() : base()
		{
		}

		public StaticFlagMenuItem(string name, string className, string field) : this() {
			this.Text = name;
			this.className = className;
			this.fieldName = field;
		}

		public StaticFlagMenuItem(MenuItem parent, string name, string className, string field) : this(name, className, field) {
			parent.MenuItems.Add(this);
			parent.Popup += new EventHandler(HandlePop);
		}

		public string className;
		Type targetClass;
		public string fieldName;
		FieldInfo field;
		PropertyInfo property;
		public bool Value {
			get {
				if (targetClass==null)
					targetClass = Meta.Utilities.SearchForType(className);
				if (field==null && property==null) {
					field = targetClass.GetField(fieldName);
					property = targetClass.GetProperty(fieldName);
				}
				if (field==null)
					return (bool)property.GetValue(targetClass, new object[0]);
				else
					return (bool)field.GetValue(targetClass);
			}
			set {
				if (targetClass==null)
					targetClass = Meta.Utilities.SearchForType(className);
				if (field==null && property==null) {
					field = targetClass.GetField(fieldName);
					property = targetClass.GetProperty(fieldName);
				}
				if (field==null)
					property.SetValue(targetClass, value, new object[0]);
				else
					field.SetValue(targetClass, value);
			}
		}

		void HandlePop(object sender, EventArgs e) {
			Checked = Value;
		}

		protected override void OnClick(EventArgs e) {
			Value = !Value;
		}
	}
}
